﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;

namespace CWB.Web.MVC.ActionResults
{
    public class BinaryResult  : ActionResult
    {
        public BinaryResult() { }

        private byte[] _fileBinary;
        private string _contentType;
        private string _fileName;

        public BinaryResult(ControllerContext context, string FileName)
        {
            context.Controller.TempData.Clear();
            _contentType = "audio/wav";
            _fileName = FileName;
            string fullfilepath = context.HttpContext.Server.MapPath(".\\..\\App_Data\\" + FileName);
            if (File.Exists(fullfilepath))
            {
                //using (FileStream fileStream = new FileStream(fullfilepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) ;
                FileStream fileStream = new FileStream(fullfilepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (fileStream.Length > 0)
                {
                    _fileBinary = new byte[(int)fileStream.Length];
                    fileStream.Read(_fileBinary, 0, _fileBinary.Length);
                    fileStream.Close();
                }
            }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context can not null or empty");
            }
            if (context.IsChildAction)
            {
                throw new InvalidOperationException("Cannot Redirect In ChildAction");
            }
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ContentType = _contentType;
            context.HttpContext.Response.AddHeader("Content-Disposition", "filename=" + _fileName);
            if (_fileBinary != null)
            {
                context.HttpContext.Response.BinaryWrite(_fileBinary);
            }
        }
    }
}
